/*
** hook.c for  in /home/guicqu_g//svn/rush-epikong/etape_2
** 
** Made by gallien guicquero
** Login   <guicqu_g@epitech.net>
** 
** Started on  Sun Mar 27 15:28:34 2011 gallien guicquero
** Last update Tue Apr 12 22:21:55 2011 gallien guicquero
*/

#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "mlx.h"
#include "window.h"

int	try(t_p *p, int x, int y)
{
  if (is_valid(p->cols, p->rows, p->h.p.x + x, p->h.p.y + y) &&
      p->map[p->h.p.y + y][p->h.p.x + x] != CHAR_WALL)
    {
      if (y == -1 && (p->map[p->h.p.y][p->h.p.x] != CHAR_LADDER ||
		      p->map[p->h.p.y - 1][p->h.p.x] == CHAR_WALL))
	return (0);
      if (x != 0)
	p->h.d = x;
      p->h.p.x += x;
      p->h.p.y += y;
      return (1);
    }
  return (0);
}

int	key_hook(int key, t_p *p)
{
  if (key == KEY_ESCAPE)
    exit(0);
  if (key == KEY_LEFT)
    try(p, -1, 0);
  if (key == KEY_RIGHT)
    try(p, 1, 0);
  if (key == KEY_UP)
    try(p, 0, -1);
  if (key == KEY_DOWN)
    try(p, 0, 1);
  return (key);
}

int	expose_hook(t_p *p)
{
  mlx_put_image_to_window(p->mlx, p->w.win, p->i.img, 0, 0);
  return (0);
}

int	gravity(t_p *p)
{
  int	i;

  if (p->map[p->h.p.y + 1][p->h.p.x] != CHAR_WALL &&
      p->map[p->h.p.y][p->h.p.x] != CHAR_LADDER &&
      p->map[p->h.p.y + 1][p->h.p.x] != CHAR_LADDER)
    {
      p->h.s = take_speed(p->h.s);
      i = 0;
      while (i < p->h.s)
	{
	  if (try(p, 0, 1))
	    ++i;
	  else
	    p->h.s = 0;
	}
      if (p->map[p->h.p.y + 1][p->h.p.x] == CHAR_WALL ||
	  p->map[p->h.p.y + 1][p->h.p.x] == CHAR_LADDER ||
	  p->map[p->h.p.y][p->h.p.x] == CHAR_LADDER)
	p->h.s = 0;
    }
  return (0);
}

int	loop_hook(t_p *p)
{
  img_calc(p);
  expose_hook(p);
  usleep(40000);
  gravity(p);
  return (0);
}
